package com.ylq.todolsitserver.controller;

import com.ylq.todolsitserver.entity.Task;
import com.ylq.todolsitserver.service.TaskService;
import com.ylq.todolsitserver.vo.TaskVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/api/tasks")
public class TaskController {

    @Autowired
    private TaskService taskService;

    /**
     * 创建任务
     * @param taskVO
     * @return
     */
    @PostMapping
    public ResponseEntity<Task> createTask(@RequestBody TaskVO taskVO) {
        log.info("创建任务: {}", taskVO);
        return new ResponseEntity<>(taskService.createTask(taskVO), HttpStatus.CREATED);
    }

    /**
     * 获取所有任务
     * @param status
     * @param priority
     * @param categoryId
     * @param upcoming
     * @return
     */
    @GetMapping
    public ResponseEntity<List<Task>> getAllTasks(
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String priority,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) Boolean upcoming) {
        log.info("获取所有任务");

        return ResponseEntity.ok(taskService.getAllTasks(status, priority, categoryId, upcoming));
    }

    /**
     * 获取单个任务
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ResponseEntity<Task> getTaskById(@PathVariable Integer id) {
        log.info("获取任务: {}", id);
        return ResponseEntity.ok(taskService.getTaskById(id));
    }

    /**
     * 更新任务
     * @param id
     * @param taskVO
     * @return
     */
    @PutMapping("/{id}")
    public ResponseEntity<Task> updateTask(@PathVariable Integer id, @RequestBody TaskVO taskVO) {
        log.info("更新任务{}: {}",id, taskVO);
        return ResponseEntity.ok(taskService.updateTask(id, taskVO));
    }

    /**
     * 删除任务
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTask(@PathVariable Integer id) {
        log.info("删除任务: {}", id);
        taskService.deleteTask(id);
        return ResponseEntity.noContent().build();
    }

    /**
     * 更新任务状态
     * @param id
     * @param statusUpdate
     * @return
     */
    @PatchMapping("/{id}/status")
    public ResponseEntity<Void> updateTaskStatus(
            @PathVariable Integer id,
            @RequestBody Map<String, String> statusUpdate) {
        log.info("更新任务{}状态: {}",id, statusUpdate);

        taskService.updateTaskStatus(id, String.valueOf(statusUpdate.get("status")));
        return ResponseEntity.ok().build();
    }
}
